package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.tools.terminal.TerminalApplication;

import javax.swing.*;
import java.awt.Dimension;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author xuedianfu
 */
public class AddGenericDB extends javax.swing.JDialog {
    
    private ClientPluginTester cpt;
    private int rowIndex = -1;

    /**
     * Creates new form AddGenericDB
     */
    public AddGenericDB(ClientPluginTester cpt, JSONObject initData) {
        super(cpt, true);
        this.cpt = cpt;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(this.cpt.getShellFrame());
        setMinimumSize(new Dimension(400, 200));
        setTitle("代码飞舞采控系统-添加GenericDB");

        initEditData(initData);
    }

    private void initEditData(JSONObject initData){
        if(initData != null){
            JSONObject client = initData.getJSONObject("client");
            jtf_id.setText(client.getString("id"));
            jtf_sql.setText(client.getString("sql"));
            rowIndex = initData.getIntValue("rowIndex");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtf_id = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtf_sql = new javax.swing.JTextField();
        jb_save = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("添加GenericDB");

        jLabel2.setText("Client id：");

        jtf_id.setText("0");
        jtf_id.setToolTipText("");
        jtf_id.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_idKeyTyped(evt);
            }
        });

        jLabel3.setText("Sql：");

        jb_save.setText("保存为命令");
        jb_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_saveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(260, 260, 260)
                        .addComponent(jLabel1)
                        .addGap(0, 238, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtf_id)
                            .addComponent(jtf_sql))))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(246, 246, 246)
                .addComponent(jb_save)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtf_id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtf_sql, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jb_save)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private String getTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    private void jb_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_saveActionPerformed
        if(jtf_sql.getText().isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "SQL语句不能为空。");
            return;
        }
        JSONObject commandParams = new JSONObject();
        commandParams.put("plugin", Command.GENERICDB_COMMAND);
        JSONObject clientJo = new JSONObject();
        clientJo.put("id", Integer.valueOf(jtf_id.getText()));
        clientJo.put("sql", jtf_sql.getText());
        commandParams.put("client", clientJo);
        if(rowIndex < 0) {
            String defaultName = "GEGERICDB-" + getTime();
            String name = (String) JOptionPane.showInputDialog(this, "如需重新起名，请输入新的名称。", "保存命令", JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
            if (name == null || name.isEmpty()) {
                name = defaultName;
            }
            cpt.addPluginParam(commandParams, name);
        }else{
            cpt.addPluginParam(commandParams, rowIndex);
        }
        setVisible(false);
    }//GEN-LAST:event_jb_saveActionPerformed

    private void jtf_idKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_idKeyTyped
        JTextField jtf = (JTextField)evt.getSource();
        if (!TerminalApplication.numbers.contains(evt.getKeyChar())) {
            evt.consume();
        }
        try{
            Integer.parseInt(jtf.getText());
            if(jtf.getText().startsWith("0")){
                jtf.setText(jtf.getText().replaceAll("^0+", ""));
            }
        }catch (Exception e){
            jtf.setText("0");
        }
    }//GEN-LAST:event_jtf_idKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jb_save;
    private javax.swing.JTextField jtf_id;
    private javax.swing.JTextField jtf_sql;
    // End of variables declaration//GEN-END:variables
}
